/**
 * 后台管理系统用户列表的业务逻辑代码
 */

const db = require("../../db/db")
const initModel = require("../../models/init-models")
const { user, scrip, middle, scrip_img } = initModel(db);
const { Op } = require("sequelize");

// 关联表关系
user.hasMany(scrip, {
  targetKey: 'id',
  foreignKey: 'user_id',
  as: "my_scrip"
})
scrip.belongsTo(user, {
  targetKey: 'id',
  foreignKey: 'user_id',
  as: "my_scrip"
})
// 纸条和纸条图片表关联
scrip.hasMany(scrip_img, {
  targetKey: "id",
  foreignKey: "scrip_id"
})
scrip_img.belongsTo(scrip, {
  targetKey: "id",
  foreignKey: "scrip_id"
})
// 使用中间表过渡查取抽取的纸条数据
user.belongsToMany(scrip, {
  through: middle,
  foreignKey: 'user_id',
  as: "gain_scrip"
});
scrip.belongsToMany(user, {
  through: middle,
  foreignKey: 'scrip_id',
  as: "gain_scrip"
});

module.exports = {
  // 用户列表
  allUser: async (req, res) => {
    // 获取页码和数据条数/用户昵称
    let { page, limit, name } = req.query;
    console.log(req.headers);
    page = page == null ? 1 : Number(page);
    limit = limit == null ? 5 : Number(limit);
    // 计算跨越的条数
    let offset = (page - 1) * limit;

    // 获取全部用户数据
    let allUser;
    if (name == null) {
      allUser = await user.findAndCountAll({
        distinct: true, // 去重不计算 include 的总条数
        include: [
          {
            model: scrip,
            as: "my_scrip",
            attributes: {exclude: ["openid"]},
            include: [
              {
                model: scrip_img,
                attributes: { exclude: ['scrip_id'] },
              }
            ]
          },
          {
            model: scrip,
            as: "gain_scrip",
            through: { attributes: [],}, // 去除中间表
            include: [
              {
                model: scrip_img,
                attributes: { exclude: ['scrip_id'] },
              }
            ]
          },

        ],
        order: [["id", "DESC"], ["gain_scrip", "id", "DESC"]],
        offset,
        limit
      });
    } else {
      allUser = await user.findAndCountAll({
        distinct: true, // 去重不计算 include 的总条数
        where: {
          user_name: {
            [Op.like]: `%${name}%`
          }
        },
        attributes: {exclude: ["openid"]},
        include: [
          {
            model: scrip,
            as: "my_scrip",
            include: [
              {
                model: scrip_img,
                attributes: { exclude: ['scrip_id'] },
              }
            ]
          },
          {
            model: scrip,
            as: "gain_scrip",
            through: { attributes: [] }, // 去除中间表
            include: [
              {
                model: scrip_img,
                attributes: { exclude: ['scrip_id'] },
              }
            ]
          }
        ],
        order: [["id", "DESC"], ["gain_scrip", "id", "DESC"]],
        offset,
        limit
      });
    }

    // 返回数据
    res.send({
      status: 200,
      msg: "获取成功",
      data: {
        count: allUser.count,
        users: allUser.rows
      }
    })
  },
  // 禁用或解封用户
  bannedUser: async (req, res) => {
    // 获取数据
    let { id, is_banned} = req.body;
    // 判断数据是否准确
    if(id == null || is_banned == null) {
      res.send({
        status: 400,
        msg: "缺少参数",
      });
      return;
    }

    // 查询用户是否存在
    let findUser = await user.findOne({
      where: {id}
    });

    // 判断是否存在
    if(findUser == null) {
      res.send({
        status: 400,
        msg: "该用户不存在",
      });
      return;
    }

    // 修改
    findUser.banned = is_banned;
    // 保存
    let saveResult = findUser.save();
    if (saveResult != null) {
      console.log(is_banned);
      res.send({
        status: 200,
        msg: is_banned == "false" ? "解封成功" : "禁用成功"
    })
    }

  },
  // id查找某个用户
  findUser: async (req, res) => {
    // 获取参数
    let {id} = req.query;
    // 判断是否传参
    if(id == null) {
      res.send({
        status: 400,
        msg: "缺少参数"
      });
      return;
    }

    let findUser = await  user.findOne({
      where: {id},
      include: [
        {
          model: scrip,
          as: "my_scrip",
          attributes: {exclude: ["openid"]},
          include: [
            {
              model: scrip_img,
              attributes: { exclude: ['scrip_id'] },
            }
          ]
        },
        {
          model: scrip,
          as: "gain_scrip",
          through: { attributes: [],}, // 去除中间表
          include: [
            {
              model: scrip_img,
              attributes: { exclude: ['scrip_id'] },
            }
          ]
        },

      ],
    })

    // 用户不存在
    if(findUser == null) {
      res.send({
        status: 400,
        msg: "该用户不存在"
      });
      return;
    }
    res.send({
      status: 200,
      msg: "获取成功",
      data: findUser
    })
  }
}